<?php

namespace app\admin\controller\games;

use app\common\controller\Backend;
use app\common\model\Config as ConfigModel;
use fast\Form;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 游戏管理
 *
 * @icon fa fa-circle-o
 */
class Tradefee extends Backend
{

    /**
     * Game模型对象
     * @var \app\admin\model\goods\Game
     */
    protected $model = null;
    protected $noNeedRight = ['gameList'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\goods\Server;
        $this->infomodel = new \app\admin\model\games\GameInfo;
        $this->gamemodel = new \app\admin\model\games\Game();
        $list = \app\admin\model\games\Game::field('id,game')->select();
        $this->view->assign("list", $list);

    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where(['game_id' => ['<>', 0]])
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'trim');
            if (empty($params['game_id'])) {
                $this->error(__('游戏名称不能为空', ''));
            }
            if (empty($params['pid'])) {
                $this->error(__('分类不能为空', ''));
            }
            if ($params['service'] == '') {
                $this->error(__('平台服务费不能为空', ''));
            }

            $pattern = '/0|0.[\d{2}]/';
            if(!preg_match($pattern,$params['service'])){
                $this->error(__('服务费格式错误', ''));
            }

            if ($params['trade'] == '') {
                $this->error(__('手续费不能为空', ''));
            }

            if(!preg_match($pattern,$params['trade'])){
                $this->error(__('手续费格式错误', ''));
            }

//            if($params['safe'] == 3){
//                if($params['xyg_fee'] == ''){
//                    $this->error(__('心意购服务费不能为空', ''));
//                }
//                $pattern1 = '/\d{1,2}\/\d{1,2}\/\d{1,2}/';
//                if(!preg_match($pattern1,$params['xyg_fee'])){
//                    $this->error(__('心意购服务费格式错误', ''));
//                }
//            }

            $infos = $this->model->where([
                'game_id' => $params['game_id'],
                'game_type' => $params['pid'],
//                'type' => $params['type'],
                'safe' => $params['safe'],
                'method' => $params['method']
            ])->find();
            if($infos){
                $this->error(__('此分类已存在，不能重复添加', ''));
            }

            $data = array(
                'game_id' => $params['game_id'],
                'game_type' => $params['pid'],
                'safe' => $params['safe'],
//                'xyg' => $params['xyg'],
                'method' => $params['method'],
//                'type' => $params['type'],
                'game_name' => $this->gamemodel::where(['id' => $params['game_id']])->field('game')->find()['game'],
                'game_sub_name'=>$this->infomodel::where(['id'=>$params['pid']])->field('name')->find()['name'],
                'service' => $params['service'],
                'trade' => $params['trade'],
//                'xyg_fee'=>$params['xyg_fee']?:'3/6/9'
                'xyg_fee'=>'3/6/9'
            );
            try {
                $result = $this->model->create($data);
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                try {
                    ConfigModel::refreshFile();
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                $this->error($this->model->getError());
            }
//            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $safe = $params['safe']?:2;
            if ($params) {
                if (empty($params['game_id'])) {
                    $this->error(__('游戏名称不能为空', ''));
                }
                if (empty($params['pid'])) {
                    $this->error(__('分类不能为空', ''));
                }
                if ($params['service'] == '') {
                    $this->error(__('平台服务费不能为空', ''));
                }

                $pattern = '/0|0.[\d{2}]/';
                if(!preg_match($pattern,$params['service'])){
                    $this->error(__('服务费格式错误', ''));
                }

                if ($params['trade'] == '') {
                    $this->error(__('手续费不能为空', ''));
                }

                if(!preg_match($pattern,$params['trade'])){
                    $this->error(__('手续费格式错误', ''));
                }
//                if($params['safe'] == 3){
//                    if($params['xyg_fee'] == ''){
//                        $this->error(__('心意购服务费不能为空', ''));
//                    }
//                    $pattern1 = '/^\d{1,2}\/\d{1,2}\/\d{1,2}$/';
//                    if(!preg_match($pattern1,$params['xyg_fee'])){
//                        $this->error(__('心意购服务费格式错误', ''));
//                    }
//                }

                $infos = $this->model->where([
                    'game_id' => $params['game_id'],
                    'game_type' => $params['pid'],
//                    'type' => $params['type'],
                    'safe' => $safe,
                    'method' => $params['method'],
                    'id'=>['<>',$params['id']]
                ])->find();
                if($infos){
                    $this->error(__('此分类已存在，不能重复添加', ''));
                }

                $data = array(
                    'game_id' => $params['game_id'],
                    'game_type' => $params['pid'],
                    'safe' => $safe,
//                    'xyg' => $params['xyg'],
                    'method' => $params['method'],
//                    'type' => $params['type'],
                    'game_name' => $this->gamemodel::where(['id' => $params['game_id']])->field('game')->find()['game'],
                    'game_sub_name'=>$this->infomodel::where(['id'=>$params['pid']])->field('name')->find()['name'],
                    'service' => $params['service'],
                    'trade' => $params['trade'],
//                    'xyg_fee'=>$params['xyg_fee']
                );

                $result = $row->allowField(true)->save($data);
//                    $result = $row->allowField(true)->save($data);
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function cxselect()
    {
        //游戏属性
        $type = $this->request->get('type');
        $game_id = $this->request->get('gameid');
        $list = array();
        if ($game_id !== '') {
            if ($type == 'game') {
                $list = $this->gamemodel::field('id as value,game as name')->select();
            } else {
                $list = $this->infomodel::where(['game_id' => $game_id, 'gt_id' => '5'])->field('id as value,name,pid')->select();
                if ($list) {
                    foreach ($list as $k => &$v) {
                        $pname = $this->infomodel::where('id', '=', $v['pid'])->column('name');
                        if ($pname) {
                            $v['name'] = $pname[0] . '--' . $v['name'];
                        }

                        unset($v['pid']);
                    }
                }
            }
        }
        $this->success('', null, $list);
    }

    public function build_checkboxs($name, $list = [], $selected = null)
    {
        $html = [];
        $selected = is_null($selected) ? [] : $selected;
        $selected = is_array($selected) ? $selected : explode(',', $selected);
        foreach ($list as $k => $v) {
            $html[] = sprintf(Form::label("{$name}-{$k}", "%s {$v}"), Form::checkbox($name, $k, in_array($k, $selected), ['id' => "{$name}-{$k}"]));
        }
        return '<div class="checkbox">' . implode(' ', $html) . '</div>';
    }
}
